#include <iostream>
#include <pthread.h>
#include <unistd.h>
int _ticket_num = 0;
pthread_mutex_t _lock;
pthread_cond_t _pct = PTHREAD_COND_INITIALIZER; // 条件变量

void *Ticket(void *_data)
{
    //>> 转化名字
    char *_name = (char *)_data;
    while (true)
    {
        pthread_mutex_lock(&_lock);
        //>> 开始抢票
        if (_ticket_num <= 0)
        {
            // pthread_mutex_unlock(&_lock);
            //>> 没有票了
            printf("%s wait on cond!\n", _name);
            pthread_cond_wait(&_pct, &_lock); // 醒来的时候 ，会重新申请锁
            printf("%s 线程被叫醒！\n", _name);
        }
        if (_ticket_num > 0)
        {
            usleep(1000);
            printf("%s get the %d ticket!\n", _name, _ticket_num); // 谁抢到了 标记一下名字和抢到的号码
            _ticket_num--;                                         // 有票 就抢
            pthread_mutex_unlock(&_lock);
        }
    }

    return nullptr;
}

int main()
{

    pthread_t _pt1, _pt2, _pt3, _pt4;
    int _cnt = 10;

    //>> 创造线程
    pthread_create(&_pt1, nullptr, Ticket, (void *)"PT1");
    pthread_create(&_pt2, nullptr, Ticket, (void *)"PT2");
    pthread_create(&_pt3, nullptr, Ticket, (void *)"PT3");
    pthread_create(&_pt4, nullptr, Ticket, (void *)"PT4");

    //>> 主线程放票
    while (true)
    {
        sleep(5);
        printf("主线程放票！\n");
        _ticket_num += _cnt;
        pthread_cond_signal(&_pct);
    }

    //>> 线程等待
    pthread_join(_pt1, nullptr);
    pthread_join(_pt2, nullptr);
    pthread_join(_pt3, nullptr);
    pthread_join(_pt4, nullptr);

    pthread_mutex_destroy(&_lock);

    return 0;
}
